package top.itpath.admin.controller;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.itpath.admin.entity.SysRole;
import top.itpath.admin.service.ISysRoleMenuService;
import top.itpath.admin.service.ISysRoleService;
import top.itpath.common.Result;
import top.itpath.common.event.UpdateRoleMenuEvent;

import java.util.List;

/**
 * 系统/角色
 *
 * @author zhaomengru
 * @time 2023/10/12 - 21:49
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
public class RoleController {

    private final ISysRoleService sysRoleService;
    private final ISysRoleMenuService roleMenuService;

    private final ApplicationEventPublisher publisher;

    /**
     * 分页查询
     *
     * @param page   页号
     * @param size   分页大小
     * @param name   搜索名称
     * @param enName 搜索英文名称
     */
    @GetMapping("/page")
    Result<?> page(@RequestParam(defaultValue = "0", required = false) Integer page,
                   @RequestParam(defaultValue = "1", required = false) Integer size,
                   @RequestParam(required = false) String name,
                   @RequestParam(required = false) String enName) {
        LambdaQueryChainWrapper<SysRole> wrapper = sysRoleService.lambdaQuery()
                .like(StringUtils.hasText(name), SysRole::getName, name)
                .like(StringUtils.hasText(enName), SysRole::getEnName, enName);
        return Result.success(sysRoleService.page(Page.of(page, size), wrapper));
    }

    /**
     * 添加角色
     *
     * @param sysRole 角色
     */
    @PostMapping("/add")
    Result<?> add(@RequestBody SysRole sysRole) {
        sysRoleService.save(sysRole);
        return Result.success(sysRole);
    }

    /**
     * 更新角色信息
     *
     * @param sysRole 新的角色信息
     */
    @PostMapping("/update")
    Result<?> update(@RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        return Result.success(sysRole);
    }

    /**
     * 删除一个角色
     *
     * @param sysRole 角色
     */
    @PostMapping("/delete")
    Result<?> delete(@RequestBody SysRole sysRole) {
        sysRoleService.removeById(sysRole.getId());
        return Result.success();
    }

    /**
     * 角色授权
     */
    @PostMapping("/authorize")
    Result<?> authorize(@RequestParam Long roleId,
                        @RequestParam List<Long> menuIds) {
        SysRole role = sysRoleService.getById(roleId);
        Assert.notNull(role, "角色不存在");
        roleMenuService.setPermission(roleId, menuIds);
        publisher.publishEvent(new UpdateRoleMenuEvent(this, role));
        return Result.success();
    }
}
